package com.tongsys.server.service.impl;

import com.tongsys.server.config.redis.RedisService;
import com.tongsys.server.config.redis.RedisUtils;
import com.tongsys.server.config.security.exception.exp;
import com.tongsys.server.entity.User;
import com.tongsys.server.service.ILoginService;
import com.tongsys.server.utils.JwtUtils;
import com.tongsys.server.utils.RtnUtils;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;


@Service
@Transactional
public class LoginServiceImpl  implements ILoginService {


    @ApiModelProperty("用户封装 生成 Authentication 对象")
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisService redisService;

    @Value("${spring.redis.expire}")
    private long expire;

    @ApiOperation("进行登录认证")
    @Override
    public RtnUtils login(User user) {

        //使用Authentication 的实现类 UsernamePasswordAuthenticationToken ，封装user 的账号和密码
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken=new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        //将 封装对象和UserDetailsService 中的 查询出来的对象 进行对比，如果成功 返回 authenticate 对象
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);

        if (Objects.isNull(authenticate)){
            //如果认证没通过，给出对应的提示
            throw new exp("登录失败");
        }
        //获取封装后的数据并强转
        User principal = (User) authenticate.getPrincipal();

        //把完整的用户信息存入redis
        redisUtils.setCacheObject ("login:"+principal.getId(), principal);
        //redisService.redisSet("logins:"+principal.getId(),principal);

        //如果认证通过了，使用userid生成一个jwt,并返回
        String token = JwtUtils.createToken(principal.getId());
        return RtnUtils.ok().data(token);
    }

    @Override
    public RtnUtils logout() {
        //获取SecurityContextHolder中的userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal = (User) authentication.getPrincipal();

        //删除redsi 中的key
        boolean b = redisUtils.deleteObject("login:"+principal.getId().toString());
        if (b){
            return RtnUtils.ok().msg("退出登录");
        }else {
            return RtnUtils.err().msg("退出失败");
        }
    }
}
